package lc.二叉树.剑指Offer;

import utils.TreeNode;

import java.util.*;

/**
 * @description:
 * @author: qian
 * @createDate: 2021/10/17
 */
public class Math剑指Offer32_Z字从上到下打印二叉树 {

    public List<List<Integer>> levelOrder(TreeNode root) {

        List<List<Integer>> list = new ArrayList<>();
        Queue<TreeNode> q = new LinkedList<>();
        if(root==null)return list;
        q.add(root);
        int target = 0;
        while (!q.isEmpty()) {

            int size = q.size();
            List<Integer> res = new ArrayList<>();
            for (int i = 0; i < size; i++) {

                TreeNode node = q.poll();
                res.add(node.val);
                if (node.left != null) q.add(node.left);
                if (node.right != null) q.add(node.right);
            }
            target++;
            if (target % 2 == 0) {
                Collections.reverse(res);
            }

            list.add(res);

        }
        return list;
    }
}
